package com.aiyan.edu.govern.zuul.filter;

import com.aiyan.edu.framework.model.response.CommonCode;
import com.aiyan.edu.framework.model.response.ResponseResult;
import com.aiyan.edu.framework.utils.CookieUtil;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 身份验证拦截器
 *
 * @author: zqzhou
 * @create: 2019/11/23 15:29
 **/
@Component
public class IdentityFilter extends ZuulFilter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 过滤器的类型
     * pre：请求被路由之前执行
     * routing：在路由请求时执行
     * post：routing和error过滤器之后执行
     * error：处理请求时发生错误时执行
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    /**
     * 验证cookie是否携带身份令牌
     * 验证header是否有携带 Authorization Bearer jwt令牌
     * <p>
     * 验证令牌的有效性
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest servletRequest = currentContext.getRequest();
        HttpServletResponse servletResponse = currentContext.getResponse();

        // 获取cookie中的身份令牌
        Map<String, String> cookie = CookieUtil.readCookie(servletRequest, "utoken");
        String utoken = cookie.get("utoken");

        if (StringUtils.isEmpty(utoken)) {
            this.setResponseDenied(CommonCode.UNAUTHENTICATED);
            return null;
        }

        // 这里只校验是否携带jwt令牌，令牌有效性由各资源服务（微服务）进行校验
        String jwt = this.getAuthorizationHeader(servletRequest);
        if (StringUtils.isEmpty(jwt)) {
            this.setResponseDenied(CommonCode.NOTOKEN);
            return null;
        }

        // 校验用户令牌是否过期
        Long expire = this.stringRedisTemplate.getExpire("user:token:" + utoken);
        if (expire < 0) {
            this.setResponseDenied(CommonCode.TOKENEXPIRES);
            return null;
        }

        return null;
    }

    private String getAuthorizationHeader(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            return null;
        }

        if (!authorization.startsWith("Bearer ")) {
            return null;
        }

        return authorization.substring(7);
    }

    private void setResponseDenied(CommonCode commonCode) {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse servletResponse = currentContext.getResponse();
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(200);

        //构建统一响应结果
        ResponseResult responseResult = new ResponseResult(commonCode);

        currentContext.setResponseBody(JSON.toJSONString(responseResult));
        servletResponse.setContentType("application/json;charset=utf-8");
    }
}
